package cn.wolfcode.luowowo.resolver;


import cn.wolfcode.luowowo.annotation.UserAnnotation;
import cn.wolfcode.luowowo.domain.UserInfo;
import cn.wolfcode.luowowo.redis.Service.IUserInfoRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

public class UserResolver implements HandlerMethodArgumentResolver{
    @Autowired
    private IUserInfoRedisService userInfoRedisService;
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //指定当前解析器能支持的参数类型
        //true为支持,false为不支持
        //只有贴有@UserAnnotation注解的才会被解析
        return methodParameter.getParameterType() == UserInfo.class
                && methodParameter.hasParameterAnnotation(UserAnnotation.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //如果supportsParameter方法返回的是true时才执行的方法
        //执行,获取当前用户信息.将返回值注入请求映射方法声明的形式参数中
        //通过请求头信息获取token,再通过token获取当前用户信息
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String token = request.getHeader("token");
        UserInfo userByToken = userInfoRedisService.getUserByToken(token);
        return userByToken;
    }
}
